import React, { Component } from 'react'

import { Card,Breadcrumb,Form,Radio,Button,DatePicker,Table,Tag,Space,Modal,message } from 'antd'
import {EditOutlined,DeleteOutlined,CloseCircleOutlined} from '@ant-design/icons'
import { Link } from 'react-router-dom'
import {Channel} from 'components/Channel/Channel'

// 样式
import styles from './articlelist.module.scss'
import defaultImg from 'assets/error.png'
//api
import { articleStatus } from 'api/someconstant'
import { deleteArticle, getArticles } from 'api/article' 
const { confirm } = Modal

export class ArticleList extends Component {
  formRef = React.createRef()
  columns = [ // 表格配置信息
    {
      title: '封面',
      render(data) {
        if(data.cover.type === 0) return <img src={defaultImg} alt="无封面" style={{width:'200px',height:'112.5px',objectFit:'cover'}} />
        return <img src={data.cover.images[0]} alt="封面" style={{width:'200px',height:'112.5px',objectFit:'cover'}} />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status){
        const statusInfo = articleStatus.find((item) => item.id === status)
        return <Tag color={statusInfo.color}>{statusInfo.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render:(data) => {
        return <Space>
          <Button type="primary" shape="circle" onClick={() => this.editArticle(data.id)} icon={<EditOutlined/>} />
          <Button type="primary" onClick={() => this.delArticlr(data.id)} danger shape="circle" icon={<DeleteOutlined/>} />
        </Space>
      }
    },
  ]
  altquery = {// 获取文章列表请求参数
    page:1,
    per_page:10,
  }
  state = {
    // 频道数据
    channelslist:[],
    // 文章列表
    articleslist:{}
  }
  render() {
    const {total_count,results,page} = this.state.articleslist
    return (
      <div className={styles.articlelist}>
        <Card title={
          <Breadcrumb>
            <Breadcrumb.Item> <Link to='/home'>首页</Link> </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb> }>
          <Form initialValues={{status:-1,channel_id:undefined,data:undefined}} ref={this.formRef} name='select_ref' onFinish={this.selectInfo}>
            <Form.Item label='状态' name='status'>
              <Radio.Group >
                {articleStatus.map((item)=><Radio key={item.id} value={item.id}>{item.name}</Radio>)}
              </Radio.Group>
            </Form.Item>
            <Form.Item className='itemfloat' label='频道' name='channel_id'>
              <Channel></Channel>
            </Form.Item>
            <Form.Item label='日期' name='data'>
              <DatePicker.RangePicker/>
            </Form.Item>
            <Form.Item>
              <Button type='primary' htmlType='submit'>提交</Button>
              <Button style={{ marginLeft: 16 }} onClick={this.handleReset}>重置</Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据筛选条件，供查询到 ${total_count} 条结果：`}>
          <Table pagination={{
            total:total_count,
            position:['bottomCenter'],
            current:page,
            onChange:this.cgPageInfo
          }} columns={this.columns} dataSource={results} rowKey='id'/>
        </Card>
      </div>
    )
  }

  componentDidMount() {
    this.getArticlesList()
  }

  async getArticlesList() { //获取文章列表数据
    const alres = await getArticles(this.altquery)
    // console.log(alres)
    this.setState({
      articleslist:alres.data
    })
  }

  selectInfo = (value) => { // 筛选内容
    // console.log(value)
    if(value.status !== -1) {
      this.altquery.status = value.status
    } else {
      delete this.altquery.status
    }

    if(value.channel_id !== undefined) {
      this.altquery.channel_id = value.channel_id
    } else {
      delete this.altquery.channel_id
    }

    if(value.data) {
      this.altquery.begin_pubdate = value.data[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.altquery.end_pubdate = value.data[1].endOf("day").format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete this.altquery.begin_pubdate
      delete this.altquery.end_pubdate
    }
    this.altquery.page = 1
    this.getArticlesList()
    // console.log(this.altquery)
  }

  handleReset = () => { // 表单重置
    this.formRef.current.resetFields()
  }

  cgPageInfo = (current, pageSize) => { // 分页变化
    // console.log(current,pageSize)
    this.altquery.page = current
    this.altquery.per_page = pageSize
    // console.log(this.altquery)
    this.getArticlesList()
  }

  editArticle = (id) => { // 修改文章
    this.props.history.push('/home/publish/'+id)
  }

  delArticlr = (id) => { // 删除文章
    // console.log(id)
    confirm({
      title: '您确定要删除这篇文章？',
      icon:<CloseCircleOutlined/>,
      onOk: async() => {
        await deleteArticle(id).catch((err) => {
          message.error(`删除失败！error:${err.response.data.message}`,1)
        })
        message.success('删除成功！',1)
        this.getArticlesList()
      },
    });
  }

}

export default ArticleList